﻿<script lang="ts" setup name="storeProcessRecord">
import { ref, reactive, onMounted } from 'vue';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ArrowRight, Edit } from '@element-plus/icons-vue';
import { downloadStreamFile } from '/@/utils/download';
import { useStoreProcessRecordApi } from '/@/api/store/storeProcessRecord';
import editDialog from '/@/views/store/storeProcessRecord/component/editDialog.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';

interface StoreProcessRecordItem {
	approvalAction?: number;
	[key: string]: unknown;
}

const storeProcessRecordApi = useStoreProcessRecordApi();
const printDialogRef = ref();
const editDialogRef = ref();
const state = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false,
	dropdownData: {} as any,
	selectData: [] as StoreProcessRecordItem[],
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
	},
	tableData: [] as StoreProcessRecordItem[],
	viewMode: 'detail', // 'detail' | 'summary' - 详细模式 | 汇总模式
});

// 页面加载时
onMounted(async () => {});

// 查询操作
const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;
	state.tableParams = Object.assign(state.tableParams, params);

	// 构建查询参数，处理最终状态筛选
	const queryParams = Object.assign({}, state.tableQueryParams, state.tableParams);

	// 如果是汇总模式且有最终状态筛选，需要特殊处理
	if (state.viewMode === 'summary' && queryParams.finalApprovalAction !== undefined) {
		// 暂时移除最终状态参数，因为后端不直接支持
		const finalApprovalAction = queryParams.finalApprovalAction;
		delete queryParams.finalApprovalAction;

		// 执行查询
		const result = await storeProcessRecordApi.pageSummary(queryParams).then((res) => res.data.result);

		// 在前端过滤最终状态
		if (finalApprovalAction !== null && finalApprovalAction !== undefined) {
			const filteredItems =
				(result?.items ?? []).filter((item: StoreProcessRecordItem) => item.approvalAction === finalApprovalAction) ?? [];
			state.tableParams.total = filteredItems.length;
			state.tableData = filteredItems;
		} else {
			state.tableParams.total = result?.total;
			state.tableData = result?.items ?? [];
		}
	} else {
		// 移除最终状态参数，使用常规查询
		delete queryParams.finalApprovalAction;

		let result;
		if (state.viewMode === 'summary') {
			result = await storeProcessRecordApi.pageSummary(queryParams).then((res) => res.data.result);
		} else {
			result = await storeProcessRecordApi.page(queryParams).then((res) => res.data.result);
		}

		state.tableParams.total = result?.total;
		state.tableData = result?.items ?? [];
	}

	state.tableLoading = false;
};

// 切换显示模式
const switchViewMode = (mode: 'detail' | 'summary') => {
	state.viewMode = mode;
	state.selectData = []; // 清空选中数据
	handleQuery({ page: 1 }); // 重新查询第一页数据
};

// 格式化日期时间
const formatDateTime = (dateTime: string | Date) => {
	if (!dateTime) return '';
	const date = new Date(dateTime);
	return date
		.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
		})
		.replace(/\//g, '-');
};

// 获取步骤状态样式类
const getStepStatusClass = (status: number) => {
	// StatusApprovalEnum 枚举值: Pending = 0, Reviewed = 1, Approved = 2, Completed = 3, Rejected = 4
	switch (status) {
		case 4: // Rejected 已拒绝
			return 'status-rejected';
		case 3: // Completed 已完成
			return 'status-completed';
		case 2: // Approved 已审批
			return 'status-approved';
		case 1: // Reviewed 已审核
			return 'status-reviewed';
		case 0: // Pending 待审核
			return 'status-pending';
		default:
			return '';
	}
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 删除
const delStoreProcessRecord = (row: any) => {
	ElMessageBox.confirm(`确定要删除吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await storeProcessRecordApi.delete({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 批量删除
const batchDelStoreProcessRecord = () => {
	ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await storeProcessRecordApi.batchDelete(state.selectData.map((u) => ({ id: u.id }))).then((res) => {
				ElMessage.success(`成功批量删除${res.data.result}条记录`);
				handleQuery();
			});
		})
		.catch(() => {});
};

// 导出数据
const exportStoreProcessRecordCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		let params;
		if (command === 'select') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
		} else if (command === 'current') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams);
		} else if (command === 'all') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
		}
		await storeProcessRecordApi.exportData(params).then((res) => downloadStreamFile(res));
	} finally {
		state.exportLoading = false;
	}
};

handleQuery();
</script>
<template>
	<div class="storeProcessRecord-container" v-loading="state.exportLoading">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
				<el-row>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item label="关键字">
							<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="审批类型">
							<el-select v-model="state.tableQueryParams.flowType" clearable placeholder="请选择审批类型">
								<el-option label="入库" value="入库" />
								<el-option label="出库" value="出库" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="申请号">
							<el-input v-model="state.tableQueryParams.requestNo" clearable placeholder="请输入申请号" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="物资名称">
							<el-input v-model="state.tableQueryParams.materialName" clearable placeholder="请输入物资名称" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="申请人姓名">
							<el-input v-model="state.tableQueryParams.applicantName" clearable placeholder="请输入申请人姓名" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="变更状态">
							<g-sys-dict v-model="state.tableQueryParams.approvalAction" code="StatusApprovalEnum" render-as="select" placeholder="请选择变更状态" clearable filterable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI && state.viewMode === 'summary'">
						<el-form-item label="最终状态">
							<g-sys-dict v-model="state.tableQueryParams.finalApprovalAction" code="StatusApprovalEnum" render-as="select" placeholder="请选择最终状态" clearable filterable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="记录时间">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.completedTimeRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item>
							<el-button-group style="display: flex; align-items: center">
								<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'storeProcessRecord:page'" v-reclick="1000"> 查询 </el-button>
								<el-button icon="ele-Refresh" @click="() => (state.tableQueryParams = {})"> 重置 </el-button>
								<el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI"> 高级查询 </el-button>
								<el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI"> 隐藏 </el-button>
								<el-button :type="state.viewMode === 'detail' ? 'primary' : 'default'" @click="switchViewMode('detail')" icon="ele-Document"> 详细模式 </el-button>
								<el-button :type="state.viewMode === 'summary' ? 'primary' : 'default'" @click="switchViewMode('summary')" icon="ele-DataAnalysis"> 汇总模式 </el-button>
								<el-button
									type="danger"
									style="margin-left: 5px"
									icon="ele-Delete"
									@click="batchDelStoreProcessRecord"
									:disabled="state.selectData.length == 0"
									v-auth="'storeProcessRecord:batchDelete'"
								>
									删除
								</el-button>
								<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportStoreProcessRecordCommand">
									<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'storeProcessRecord:export'"> 导出 </el-button>
									<template #dropdown>
										<el-dropdown-menu>
											<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
											<el-dropdown-item command="current">导出本页</el-dropdown-item>
											<el-dropdown-item command="all">导出全部</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
							</el-button-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table
				:data="state.tableData"
				@selection-change="
					(val: any[]) => {
						state.selectData = val;
					}
				"
				style="width: 100%"
				v-loading="state.tableLoading"
				tooltip-effect="light"
				row-key="id"
				@sort-change="sortChange"
				border
			>
				<el-table-column type="selection" width="40" align="center" fixed="left" v-if="auth('storeProcessRecord:batchDelete') || auth('storeProcessRecord:export')" />
				<el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
				<el-table-column prop="flowType" label="审批类型" width="100" align="center" fixed="left" show-overflow-tooltip />
				<el-table-column prop="requestNo" label="申请号" width="140" show-overflow-tooltip />
				<el-table-column prop="storeTypeDisplayName" label="分类" fixed="left" width="150" show-overflow-tooltip />
				<el-table-column prop="materialName" label="物资名称" fixed="left" width="150" show-overflow-tooltip />
				<el-table-column prop="quantity" label="申请数量" width="80" align="center" show-overflow-tooltip>
					<template #default="scope">
						<div v-if="state.viewMode === 'summary' && scope.row.quantityChanged" class="quantity-changed">
							<div class="original-quantity">原始: {{ scope.row.originalQuantity }}</div>
							<div class="final-quantity">最终: {{ scope.row.quantity }}</div>
							<el-icon class="change-icon"><Edit /></el-icon>
						</div>
						<span v-else>{{ scope.row.quantity }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="unit" label="单位" width="80" align="center" show-overflow-tooltip />
				<el-table-column prop="applicantName" label="申请人" width="100" show-overflow-tooltip />
				<el-table-column prop="confirmerName" :label="state.viewMode === 'summary' ? '最终确认人' : '确认人'" width="100" show-overflow-tooltip />
				<el-table-column prop="completedTime" :label="state.viewMode === 'summary' ? '最终完成时间' : '记录时间'" width="150" show-overflow-tooltip />
				<el-table-column prop="approvalAction" :label="state.viewMode === 'summary' ? '最终状态' : '变更状态'" width="100" align="center" show-overflow-tooltip>
					<template #default="scope">
						<span :class="getStepStatusClass(scope.row.approvalAction)">
							<g-sys-dict v-model="scope.row.approvalAction" code="StatusApprovalEnum" />
						</span>
					</template>
				</el-table-column>
				<el-table-column label="审批流程" min-width="300" show-overflow-tooltip v-if="state.viewMode === 'summary'">
					<template #default="scope">
						<div class="process-flow" v-if="scope.row.processSteps && scope.row.processSteps.length > 0">
							<span v-for="(step, index) in scope.row.processSteps" :key="index" class="process-step">
								<span :class="getStepStatusClass(step.status)">
									<g-sys-dict :model-value="step.status" code="StatusApprovalEnum" />
								</span>
								<span class="step-info"> ({{ step.confirmer }}, {{ formatDateTime(step.time) }}) </span>
								<el-icon v-if="index < scope.row.processSteps.length - 1" class="arrow-icon">
									<ArrowRight />
								</el-icon>
							</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="变更说明" min-width="200" show-overflow-tooltip v-if="state.viewMode === 'detail'" />
				<el-table-column label="修改记录" width="100" align="center" show-overflow-tooltip v-if="state.viewMode === 'detail'">
					<template #default="scope">
						<ModifyRecord :data="scope.row" />
					</template>
				</el-table-column>
				<el-table-column label="操作" width="80" align="center" fixed="right" show-overflow-tooltip v-if="auth('storeProcessRecord:delete')">
					<template #default="scope">
						<el-button icon="ele-Delete" size="small" text type="primary" @click="delStoreProcessRecord(scope.row)" v-auth="'storeProcessRecord:delete'"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:currentPage="state.tableParams.page"
				v-model:page-size="state.tableParams.pageSize"
				@size-change="(val: any) => handleQuery({ pageSize: val })"
				@current-change="(val: any) => handleQuery({ page: val })"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100, 200, 500]"
				:total="state.tableParams.total"
				size="small"
				background
			/>
			<printDialog ref="printDialogRef" :title="'打印审批流程记录'" @reloadTable="handleQuery" />
			<editDialog ref="editDialogRef" @reloadTable="handleQuery" />
		</el-card>
	</div>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

.process-flow {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	gap: 8px;
	line-height: 1.5;
}

.process-step {
	display: flex;
	align-items: center;
	white-space: nowrap;
}

.step-info {
	font-size: 12px;
	color: #666;
	margin-left: 4px;
}

.arrow-icon {
	margin: 0 8px;
	color: #409eff;
	font-size: 14px;
}

:deep(.process-flow .el-tag) {
	margin-right: 0;
}

/* 状态颜色标识 */
.status-rejected :deep(.el-tag) {
	background-color: #fef0f0 !important;
	border-color: #fbc4c4 !important;
	color: #f56c6c !important;
	font-weight: 500;
}

.status-completed :deep(.el-tag) {
	background-color: #f0f9ff !important;
	border-color: #b3d8ff !important;
	color: #409eff !important;
	font-weight: 500;
}

.status-approved :deep(.el-tag) {
	background-color: #f0f9f0 !important;
	border-color: #b3d9b3 !important;
	color: #67c23a !important;
	font-weight: 500;
}

.status-reviewed :deep(.el-tag) {
	background-color: #fdf6ec !important;
	border-color: #f5dab1 !important;
	color: #e6a23c !important;
	font-weight: 500;
}

.status-pending :deep(.el-tag) {
	background-color: #f4f4f5 !important;
	border-color: #d3d4d6 !important;
	color: #909399 !important;
	font-weight: 500;
}

/* 数量变更显示样式 */
.quantity-changed {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 2px;
	padding: 4px;
	background-color: #fff7e6;
	border: 1px solid #ffd591;
	border-radius: 4px;
	position: relative;
}

.original-quantity {
	font-size: 12px;
	color: #999;
	text-decoration: line-through;
}

.final-quantity {
	font-size: 14px;
	color: #333;
	font-weight: 500;
}

.change-icon {
	position: absolute;
	top: 2px;
	right: 2px;
	font-size: 12px;
	color: #e6a23c;
}
</style>
